/**
 * Copyright (c) 2010 BullionXpress.com,
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */
package com.bullionxpress.client.view;

import java.awt.BorderLayout;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableColumnModel;

import com.bullionxpress.client.application.ClientGlobals;
import com.bullionxpress.shared.model.Transaction;
import com.bullionxpress.shared.listeners.AccountEvent;
import com.bullionxpress.shared.listeners.AccountListener;
import com.bullionxpress.shared.service.TransactionService;
import com.bullionxpress.shared.util.Log;

/**
 *
 * @author BullionXpress.com
 */
public class TransactionListView extends JPanel implements AccountListener {

    JTable table = null;
    //Account account = null;
    private static final int TRANSACTION_ID = 0;
    private static final int INSTRUMENT = 1;
    private static final int TIMESTAMP = 2;
    private static final int PRICE = 3;
    private static final int UNITS = 4;
    private static final int BUYER_ID = 5;
    private static final int SELLER_ID = 6;
    private static final int TOTAL = 7;
    private static final int TYPE = 8;


    public TransactionListView() {
        String[] columnNames = new String[]{"Transaction ID", "Instrument", "Timestamp", "Price", "Units", "Buyer Id", "Seller Id", "Total", "Type"}; // BALANCE ?
        ClientGlobals.cm.addAccountListener(this);
        for (int i = 0; i < columnNames.length; i++) {
            model.addColumn(columnNames[i]);
        }
        table = new JTable(model);
        //TODO: REFACTOR
        TableColumnModel tcm = table.getColumnModel();
        tcm.getColumn(PRICE).setCellRenderer(new DollarCellRenderer());
        tcm.getColumn(UNITS).setCellRenderer(new NumberCellRenderer());
        tcm.getColumn(TOTAL).setCellRenderer(new DollarCellRenderer());

        setLayout(new BorderLayout());
        add(table.getTableHeader(), BorderLayout.NORTH);
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane, BorderLayout.CENTER);

    }
    GenericTableModel model = new GenericTableModel();

    private boolean containsTransaction(String tid) {
        try {
            for (int i = 0; i < model.getRowCount(); i++) {
                String id = (String) model.getValueAt(i, TRANSACTION_ID);
                if (id.equals(tid)) {
                    return true;
                }
            }
        } catch (Exception ex) {
        }
        return false;
    }

    private void updateTransaction(Transaction t) {
    }

    public void update(AccountEvent ae) {
        try {
            TransactionService om = ClientGlobals.transactionService;

            //while (model.getRowCount() > 0) {
            //    model.removeRow(0);
            //}

            java.util.Queue q = om.getTransactionListByAccount(ClientGlobals.account.getId());
            if( q != null ){
                Object[] data = q.toArray();
                DecimalFormat format = new DecimalFormat("#,##0.00");
                for (int i = 0; i < data.length; i++) {
                    Transaction t = (Transaction) data[i];
                    Date d = new Date(t.getTimestamp());
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String ts = formatter.format(d);
                    if (!containsTransaction(t.getId())) {
                        Object[] row = new Object[]{
                            t.getId(), t.getInstrument().getSymbol(), ts, format.format(t.getPrice()), t.getUnits(), t.getBuyerId(), t.getSellerId(), format.format(t.getPrice() * t.getUnits()), t.getType().toString()
                        };
                        model.addRow(row);
                    } else {
                        updateTransaction(t);
                    }
                    //model.
                }

                if (data.length != model.getRowCount()) {
                    Log.info("That is odd");
                }
            }

        } catch (Exception ex) {
            Log.info(ex);
            ex.printStackTrace();
        }

    }
}
